import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:get/get.dart' hide Response;

import '../../util/HDNavigator.dart';
import '../../util/LoadingUtils.dart';
import '../../util/log_util.dart';
import '../DioClient.dart';
import 'HttpUtil.dart';
import 'Log.dart';
import 'ResponseData.dart';

///{
//   "code": "BASE_100001",
//   "msg": "",
//   "success": false,
//   "msgNo": "EMN-02-01-220617135240-000013",
//   "data": null
// }
///拦截器 处理返回的数据
class ResponseInterceptor extends InterceptorsWrapper {

  //处理服务起返回的数据
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (response.requestOptions.extra["hideLoading"] != true) {
      LoadingUtils.dismiss();
    }

    if (response.statusCode == 200) {
      //访问正确有返回值的情况
      try {
        if (response.data is String) {
          response.data = jsonDecode(response.data);
        }
        if (response.data is Map) {
          //将数据脱壳返回自己的数据 后续还要单独处理
          ResponseData responseData = ResponseData.fromJson(response.data);

          if (responseData.success) {
            responseData.isok = true;
            response.data = responseData;
            HttpUtil.BusinessDeal(response, responseData);
          } else {
            responseData.isok = false;
            //表示返回数据格式里没有 code和data 是其他格式 坐等扩展
            //请查阅返回数据格
          }
          return handler.resolve(response);
        } else {
          //表示返回格式有问题
        }
        return handler.resolve(response);
      } on Exception {
        return handler.resolve(response);
      }
    } else {
      return handler.resolve(response);
    }
  }

  @override
  Future<void> onError(DioError err, ErrorInterceptorHandler handler) async {
    print("onError => $err");
    dynamic errorMsg;

    var options = err.requestOptions;
    var url = "${options.baseUrl}${options.path}";

    bool hideLoading = err.requestOptions.extra["hideLoading"] != true;
    bool hideNetError = err.requestOptions.extra["hideNetError"] ?? false;

    if (url.contains("/insp/service/position/save")) {
      errorMsg = "${err.error}";

      if (hideLoading) {
        LoadingUtils.dismiss();
      }
    } else {
      errorMsg = await HttpUtil.DealNetworkError(err,hideLoading,hideNetError);
    }

    //表示构造返回的对象
    Map<String, dynamic> temp = {};
    temp["code"] = "-1";
    temp["msg"] = errorMsg; //err.message;
    temp["data"] = err.toString();
    ResponseData responseData = ResponseData.fromJson(temp);
    responseData.isok = false;

    //用 hander.resolve 返回处理异常之后的结果 err.response??
    handler.resolve(Response(data: responseData, requestOptions: err.requestOptions));
  }
}
